//
//  iBioCAD_Controller.m
//  iBioCAD
//
//  Created by Orbitus on 9/13/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "iBioCAD_Controller.h"
#import "File.h"
#import "Importer.h"

@implementation iBioCAD_Controller
- (void) awakeFromNib
{	
	/*id duration = [[NSUserDefaults standardUserDefaults] objectForKey:@"layoutDuration"];
    if (duration == nil) {
        duration = [NSNumber numberWithDouble:2.5];
        [[NSUserDefaults standardUserDefaults] setObject:duration forKey:@"layoutDuration"];
	*/	

	id fileManager = [NSFileManager defaultManager];

    NSString *installLocationFilePath = [[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent]
										 stringByAppendingPathComponent:@"installLocation.txt"];
	installationLocation = @"";
	
	desktopFolder = @"/Sequences/iBioCAD/Desktop";
	
    if ( [fileManager fileExistsAtPath:installLocationFilePath isDirectory:NULL] ) {
		installationLocation = [NSString stringWithContentsOfFile:installLocationFilePath];
    }
	else
	{
		//run installation script to ask to locate or install the programs
		[installationPanelController showWindow:self];
	}
//	installationPathControl = [[NSPathControl alloc] init] NEEDS SETTING
	NSLog(@"install location from iBioCADController:   %@",installationLocation);
	[installationLocation retain];
/*		

		//The location the installer is going to read from is fixed
		installationLocation = [NSString stringWithContentsOfFile:installLocationFilePath];
*/		
	
	[myImporter setInstallationFolderPath:installationLocation];
	
	//*********//
	
	[self willChangeValueForKey:@"files"];
	

	NSString* myDataPath = 	[[[[NSBundle mainBundle] bundlePath] 
							  stringByDeletingLastPathComponent]
							 stringByAppendingString:@"/Sequences/iBioCAD/"];
	
	NSMutableArray *foo = [NSMutableArray new];
	[self setFiles:foo];
	[foo release];
	File *file = [[File alloc] initWithPath: myDataPath];
	[files addObject:file];
	[file release];
	[self didChangeValueForKey:@"files"];

}
-(IBAction)test:(id)sender
{
	NSLog(@"install location from test:   %@",installationLocation);
}

- (IBAction)runInstaller:(id)sender
{
	//Installer will Write a file out with the location
	NSAppleScript *installScript;
	
	// Pass him in the myInstallAppLocation NSString
	installScript = [[NSAppleScript alloc] initWithSource:@"tell application \"iBioCAD_Installer\"\n activate \n end tell"];
	[installScript executeAndReturnError:nil];
	[installationPanelController close];
	//Let the installer script back the location of the installation....for now we use defaults!
		
}

- (NSString *)applicationSupportFolder {
	
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
    return [basePath stringByAppendingPathComponent:@"iBioCAD"];
}
- (NSManagedObjectModel *)managedObjectModel {
	
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
	
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    
    return managedObjectModel;
}

- (NSPersistentStoreCoordinator *) persistentStoreCoordinator {
	
    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }
	
    NSFileManager *fileManager;
    NSString *applicationSupportFolder = nil;
    NSURL *url;
    NSError *error;
    
    fileManager = [NSFileManager defaultManager];
    applicationSupportFolder = [self applicationSupportFolder];
    if ( ![fileManager fileExistsAtPath:applicationSupportFolder isDirectory:NULL] ) {
        [fileManager createDirectoryAtPath:applicationSupportFolder attributes:nil];
    }
    
    url = [NSURL fileURLWithPath: [applicationSupportFolder stringByAppendingPathComponent: @"iBioCAD.sql"]];
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error]){
        [[NSApplication sharedApplication] presentError:error];
    }    
	
    return persistentStoreCoordinator;
}
- (NSManagedObjectContext *) managedObjectContext {
	
    if (managedObjectContext != nil) {
        return managedObjectContext;
    }
	
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator: coordinator];
    }
    
    return managedObjectContext;
}


-(void) desktopFolder: (NSString *) newDesktopFolder
{
	[desktopFolder release];
	desktopFolder = [newDesktopFolder retain];
}

-(NSString *) desktopFolder
{
	return [[desktopFolder retain] autorelease];
}

-(NSMutableArray*) files{
	return [[files retain] autorelease];
}
-(void) setFiles: (NSMutableArray*) myFiles{
	[files release];
	files = [myFiles retain];
}
-(void) openFiles:(id)myFiles
{
	id myImporter = [[Importer alloc] init];
	[myImporter openFiles:myFiles];
}

- (IBAction) saveAction:(id)sender {
	
    NSError *error = nil;
    if (![[self managedObjectContext] save:&error]) {
        [[NSApplication sharedApplication] presentError:error];
    }
}


- (IBAction)export:(id)sender
{/*
	
	if ( [[exportName stringValue] isEqualToString:@""])
	{
		[exportName setString:@"Untitled"];
	}
	[dnaFetch setEntity: dnaEntity];
	[dnaFetch setSortDescriptors: dnaSortDescriptors];	
	
	//Every sequence that is true for export will be added to an array
	//Perform Sequences fetch with custom predicate for export status
	predicate = [NSPredicate predicateWithFormat:@"export == 1"];
	[dnaFetch setPredicate:predicate];
	NSArray * dnaExportList = [managedObjectContext executeFetchRequest:dnaFetch error:nil];
	
	//take that array and spit each name/sequence as a large fasta file
	//Output this file onto the friendly iBioCAD desktop
	NSBundle*	myBundle	= [NSBundle mainBundle];
	NSString*	myAppPath	= [myBundle bundlePath];
	NSString*	myAppFolderPath	= [myAppPath stringByDeletingLastPathComponent];
	NSString*	myDesktopFolderPath	= [myAppFolderPath stringByAppendingPathComponent: @"/desktop"];
	NSString* myOutFilePath = [[myDesktopFolderPath stringByAppendingPathComponent:[exportName stringValue]] stringByAppendingString:@".fasta"];
	
	FILE * outFile = fopen([myOutFilePath UTF8String],"w");
	int i;
	for (i=0; i <[dnaExportList count]; i++)
	{
		//THere is no new line at the end of name because name has a newline already...I don't want 2
		fprintf(outFile,"%s",[[[dnaExportList objectAtIndex:i] valueForKey:@"name"] UTF8String]);
		fprintf(outFile,"%s\n",[[[dnaExportList objectAtIndex:i] valueForKey:@"sequence"] UTF8String]);
	}
	
	//convert that file to the desired format
	//NSTask with seqret
	NSString*	seqretPath	=
	[myAppFolderPath stringByAppendingPathComponent: @"/bin/EMBOSS/emboss/seqret"];
	NSString* chosinFormat = @"";
	
	switch ([[exportFormat selectedItem] tag]) {
		case 0:
			chosinFormat = @"acedb";
			break;
		case 1:
			chosinFormat = @"asn1";
			break;
		case 2:
			chosinFormat = @"aln";
			break;
		case 3:
			chosinFormat = @"codata";
			break;
		case 4:
			chosinFormat = @"debug";
			break;
		case 5:
			chosinFormat = @"embl";
			break;
		case 6:
			chosinFormat = @"fasta";
			break;
		case 7:
			chosinFormat = @"fitch";
			break;
		case 8:
			chosinFormat = @"gcg";
			break;
		case 9:
			chosinFormat = @"gcg8";
			break;
		case 10:
			chosinFormat = @"genbank";
			break;
		case 11:
			chosinFormat = @"hennig86";
			break;
		case 12:
			chosinFormat = @"ig";
			break;
		case 13:
			chosinFormat = @"jackknifer";
			break;
		case 14:
			chosinFormat = @"jackknifernon";
			break;
		case 15:
			chosinFormat = @"mega";
			break;
		case 16:
			chosinFormat = @"meganon";
			break;
		case 17:
			chosinFormat = @"msf";
			break;
		case 18:
			chosinFormat = @"pir";
			break;
		case 19:
			chosinFormat = @"ncbi";
			break;
		case 20:
			chosinFormat = @"nexus";
			break;
		case 21:
			chosinFormat = @"nexusnon";
			break;
		case 22:
			chosinFormat = @"pearson";
			break;
		case 23:
			chosinFormat = @"phylip";
			break;
		case 24:
			chosinFormat = @"phylip3";
			break;
		case 25:
			chosinFormat = @"staden";
			break;
		case 26:
			chosinFormat = @"strider";
			break;
		case 27:
			chosinFormat = @"swiss";
			break;
		case 28:
			chosinFormat = @"text";
			break;
		case 29:
			chosinFormat = @"treecon";
			break;
		default:
			break;
	}
	
	NSTask *seqret = [[NSTask alloc] init];
	NSPipe *pipe = [[NSPipe alloc] init];
	NSFileHandle *handle;
	[seqret	setLaunchPath:seqretPath];
	[seqret setCurrentDirectoryPath:@"./desktop"];
	NSMutableArray* seqretArguments = [[NSMutableArray alloc]	init];
	[seqretArguments addObject:@"-sequence"];
	[seqretArguments addObject:myOutFilePath];
	if ([exportOption state] == 1){
		[seqretArguments addObject:@"-ossingle"];	
	} 
	[seqretArguments addObject:@"-osf"];
	[seqretArguments addObject:chosinFormat];
	[seqretArguments addObject:@"-outseq"];
	[seqretArguments addObject:[[exportName stringValue] stringByAppendingPathExtension:chosinFormat]];
	[seqretArguments addObject:@"-auto"];	
	[seqret setArguments:seqretArguments];
	
	[seqret setStandardOutput:pipe];
	[seqret launch];
	[seqret terminate];
	[seqret release];
	seqret = nil;
	//during which we spit to either the seqretsplit or seqret OR use -ossingle option*/
}

- (void) dealloc {
	
    [managedObjectContext release], managedObjectContext = nil;
    [persistentStoreCoordinator release], persistentStoreCoordinator = nil;
    [managedObjectModel release], managedObjectModel = nil;
    [super dealloc];
}

@end
